package com.example.fashion.android.MultiMedia.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.fashion.android.R;
import com.example.fashion.android.util.ImageUtil.ImageUtil;
import com.example.fashion.android.view.CameraPreview;

/**
 *@Description:
 * @author
 * @date 2016年3月18日 上午9:34:25
 */
public class CameraActivity2 extends Activity
        implements CameraPreview.OnCameraStatusListener,OnClickListener {

    //系统图片的uri地址
    public static final Uri IMAGE_URI = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    //图片的保存路径
    public static final String PATH = Environment.getExternalStorageDirectory().toString() + "/AndroidMedia/";
    //sufaceView控件
    private CameraPreview mCameraPreview;
    //聚焦成功时显示的图片
    private ImageView focusView;
    // 是否处于拍照中
    private boolean isTaking = false;
    // 是否自动对焦
    private boolean isAutoFocus;
    //拍照按钮
    private Button mBtnTakePicture;
    //相机对象
    private Camera camera;
    //切换摄像头按钮
    private Button mSwitchCamera;




    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 设置全屏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        // 照相预览界面
        setContentView(R.layout.activity2_camera);
        // 照相预览界面
        mCameraPreview = (CameraPreview) findViewById(R.id.preview);
        mBtnTakePicture = (Button) findViewById(R.id.btn_take_picture);
        mSwitchCamera = (Button) findViewById(R.id.btn_swich_camera);
        mSwitchCamera.setOnClickListener(this);
        findViewById(R.id.flash_btn).setOnClickListener(this);

        mCameraPreview.setOnCameraStatusListener(this);
        mCameraPreview.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN && !isTaking) {
                    if (camera != null) {
                        camera.autoFocus(autofocuscallback);
                        System.out.println("----> onTouch");
                    }

                }
                return false;

            }
        });


        mBtnTakePicture.setOnClickListener(this);
        // 焦点图片
        focusView = (ImageView) findViewById(R.id.focusView);
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        isAutoFocus = prefs.getBoolean("preferences_autoFocus", false);
    }

    /**
     * 自动对焦的回调
     */
    private AutoFocusCallback autofocuscallback = new AutoFocusCallback() {

        @Override
        public void onAutoFocus(boolean success, Camera camera) {
            // TODO Auto-generated method stub
            System.out.println("----->> onAutoFocus ");
        }
    };

    /**
     * 触屏事件
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN && !isTaking) {
//          isTaking = true;
//          mCameraPreview.takePicture(isAutoFocus);
        }
        return super.onTouchEvent(event);
    }

    /**
     * 存储图像并将信息添加入媒体数据库
     */
    private Uri insertImage(ContentResolver cr, String name, long dateTaken, String directory, String filename,
                            Bitmap source, byte[] jpegData) {

        OutputStream outputStream = null;
        String filePath = directory + filename;
        try {
            File dir = new File(directory);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(directory, filename);
            if (file.createNewFile()) {
                outputStream = new FileOutputStream(file);
                if (source != null) {
                    source.compress(CompressFormat.JPEG, 75, outputStream);
                } else {
                    outputStream.write(jpegData);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (Throwable t) {
                }
            }
        }
        ContentValues values = new ContentValues(7);
        values.put(MediaStore.Images.Media.TITLE, name);
        values.put(MediaStore.Images.Media.DISPLAY_NAME, filename);
        values.put(MediaStore.Images.Media.DATE_TAKEN, dateTaken);
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        values.put(MediaStore.Images.Media.DATA, filePath);
        return cr.insert(IMAGE_URI, values);
    }

    /**
     * 相机拍照结束事件
     */
    @Override
    public void onCameraStopped(byte[] data,int cameraPosition) {

        // 创建图像
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
        //旋转图片
        Bitmap rotateBitmap;
        if (cameraPosition == Camera.CameraInfo.CAMERA_FACING_BACK) {
            rotateBitmap = ImageUtil.rotateBitmapByDegree(bitmap, -90);
        } else {
            rotateBitmap = ImageUtil.rotateBitmapByDegree(bitmap, 90);
        }
        // 系统时间
        long dateTaken = System.currentTimeMillis();
        // 图像名称
        String filename = DateFormat.format("yyyy-MM-dd kk.mm.ss", dateTaken).toString() + ".jpg";
        // 存储图像（PATH目录）
        Uri uri = insertImage(getContentResolver(), filename, dateTaken, PATH, filename, rotateBitmap, data);
        // 返回结果
        Intent intent = getIntent();
        intent.putExtra("uriStr", uri.toString());
        intent.putExtra("dateTaken", dateTaken);
         intent.putExtra("filePath", PATH + filename);
         intent.putExtra("orientation", cameraPosition);  // 拍摄方向
        setResult(RESULT_OK, intent);

        finish();
    }

    /**
     * 获得图片真实路径
     *
     * @param context
     * @param uri
     * @return
     */
    public String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    /**
     * 拍摄时自动对焦事件
     */
    @Override
    public void onAutoFocus(boolean success) {
        // 改变对焦状态图像
        if (success) {
            Toast.makeText(getApplicationContext(),"聚焦成功",Toast.LENGTH_SHORT).show();
//            focusView.setImageResource(R.drawable.right);
        } else {
            Toast.makeText(getApplicationContext(),"聚焦失败",Toast.LENGTH_SHORT).show();
//            focusView.setImageResource(R.drawable.wrong);
            Toast.makeText(this, "焦距不准，请重拍！", Toast.LENGTH_SHORT).show();
            isTaking = false;
        }
    }


    private boolean isFlashOpen ;
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_take_picture:     //拍照
                isTaking = true;
                mCameraPreview.takePicture(isAutoFocus);
                break;
            case R.id.btn_swich_camera:     //切换摄像头
                mCameraPreview.switchCamera();
                break;
            case R.id.flash_btn:    //闪光灯
                ImageView flash = (ImageView)v;
                flash.setImageResource((isFlashOpen = !isFlashOpen)?R.drawable.close_lamp:R.drawable.flash_auto);

                mCameraPreview.toogleFlash();
                break;
            default:
                break;
        }

    }

    /**
     * 触摸屏幕对焦事件
     */
    @Override
    public void onTouchFocus(Camera mCamera) {
        camera = mCamera;
    }
}